/**
 * 
 */
package com.capgemini.commons;

import com.capgemini.core.AppContext;
import com.capgemini.core.BaseException;
import com.capgemini.remind.service.CommonsService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Annson
 *
 */
public class HttpSMSProcessUtil {
    
    private static Logger logger = LoggerFactory.getLogger(HttpSMSProcessUtil.class);
    
    public static String sendMessage(String smsContent, String mobilePhone) {
        List<String> mobileList = new ArrayList<String>();
        mobileList.add(mobilePhone);

       return sendMessage(smsContent, mobileList);
    }

    /**
     * 发送一条短信给多个手机号码，通道目前最大支持 1000个手机号码
     *
     * @param smsContent
     * @param mobilePhoneList
     * @return
     */
//    public static String sendMessage(String smsContent, List<String> mobilePhoneList) {
//        logger.info("smsContent：{}", smsContent);
//
//        for (String mobile : mobilePhoneList) {
//            logger.info(mobile);
//        }
//
//        return System.currentTimeMillis() + "";
//    }
    public static String sendMessage(String smsContent, List<String> mobilePhoneList){
    	String result = "";
        URL u = null;
        HttpURLConnection con = null;
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;

        CommonsService commonsService = AppContext.getBean("commonsService");
        String configJsonStr = commonsService.getCodeValueByCodeTypeAndCode("httpSMSConfig", "httpSMSConfig");

        HttpSMSProperties httpSMSProperties = null;
        try {
            httpSMSProperties = JsonUtil.fromJson(configJsonStr, HttpSMSProperties.class);
        } catch (IOException e) {
            throw new BaseException("ERROR", "短信通道参数配置错误，请联系管理员", e);
        }

//        if(!StringUtils.equalsIgnoreCase("1", httpSMSProperties.getIsSend())){
        if(!commonsService.isSendSMS()){
            return null;
        }

        //尝试发送请求
        try {
            StringBuilder url = new StringBuilder();
            url.append(httpSMSProperties.getUrl())
                    .append("?username=").append(httpSMSProperties.getUsername())
                    .append("&password=").append(httpSMSProperties.getPassword())
                    .append("&message=").append(URLEncoder.encode(smsContent, httpSMSProperties.getEncoding()));

            for (String s : mobilePhoneList) {
                url.append("&mobile=").append(s);
            }
            
            u = new URL(url.toString());
            con = (HttpURLConnection) u.openConnection();

            con.setRequestMethod("GET");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.connect();
            //add
            
            // 获取服务器响应代码
            int responsecode = con.getResponseCode();
            //读取返回内容
            if(200 == responsecode){
                try {
                    //读取返回内容
                    inputStream = con.getInputStream();
                    baos = new ByteArrayOutputStream();
                    int i = -1;
                    while ((i = inputStream.read()) != -1) {
                        baos.write(i);
                    }
                    result = baos.toString();
                    
                } catch (Exception e) {
                    logger.error("sendMessage",e);
                    result = "-error";
                }finally{
                    if(inputStream != null){
                        inputStream.close();
                    }
                    if(baos != null){
                        baos.close();
                    }
                }
            }
        } catch (Exception e) {
            logger.error("sendMessage",e);
        } finally {
            if (con != null) {
                con.disconnect();
            }
            
        }
        return result;
    }

}
